Mrli
别装作很努力,
因为结局不会陪你演戏。
Contacts:
QQ博客园

Python Web——Django笔记(二)

2019/09/15 Python 后端 Django
Word count: 2,048 | Reading time: 10min

Method= POST的操作

在posting.html中的<form>中加入标识符

1
2
3
4
> {% csrf_token %}
> <form name='my form' action='.' method='POST'>
> {% csrf_token %}
>

▲注意action='???'

1
2
3
4
5
6
7
8
9
10
在views.posting处理函数中改用RequestContext作为网页显示的内容:
from django.template import RequestContext
def posting(request):
template = get_template('posting.html')
moods = models.Mood.objects.all()
message = '如果....'
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(context=locals(), request=request)
return HttpResponse(html)

窗体Form与ModelForm区别

Form 的所有选项都是自己在forms.py 中class定义的一个类,而ModelForm则是直接引用写好的models.py中的模型.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from django import forms
class ContactForm(forms.Form):
CITY = [
['TP', 'Taipei'],
['TY', 'Taoyuang'],
['TC', 'Taichung'],
['TN', 'Tainan'],
['KS', 'Kaohsiung'],
['NA', 'Others'],
]
user_name = forms.CharField(label='你的姓名',max_length=50,initial='李大仁')
user_city = forms.ChoiceField(label='居住的城市',choices=CITY)
user_school = forms.BooleanField(label='是否在学',required=False)
user_email = forms.EmailField(label='电子邮件')
user_message = forms.CharField(label='你的意见',widget=forms.Textarea)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
-----------------------------------------------------------------------------------------<!--posting.html-->
{% extends "base.html" %}
{% block title %}我有话要说{% endblock %}
{% block content %}
<div class='container'>
{% if message %}
<div class='alert alert-warning'>{{ message }}</div>
{% endif %}
<form name='my form' action='/' method='POST'>
{% csrf_token %}
现在的心情:<br/>
{% for m in moods %}
<input type='radio' name='mood' value='{{ m.status }}'>{{ m.status }}
{% endfor %}
<br/>
心情留言板:<br/>
<textarea name='user_post' rows=3 cols=70></textarea><br/>
<label for='user_id'>你的昵称:</label>
<input id='user_id' type='text' name='user_id'>
<label for='user_pass'>张贴/删除密码:</label>
<input id='user_pass' type='password' name='user_pass'><br/>
<input type='submit' value='张贴'>
<input type='reset' value='清除重填'>
</form>
</div>
{% endblock %}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!-- index.html (ch08www project) --> 
{% extends "base.html" %}
{% block title %}我有话要说{% endblock %}
{% block content %}
<div class='container'>
{% if message %}
<div class='alert alert-warning'>{{ message }}
</div>
{% endif %}
<form name='my form' action='/' method='POST'>
{% csrf_token %}
现在的心情:<br/>
{% for m in moods %}
<input type='radio' name='mood' value='{{ m.status }}'>{{ m.status }}
{% endfor %}
<br/> 心情留言板:<br/>
<textarea name='user_post' rows=3 cols=70></textarea><br/>
<label for='user_id'>你的昵称:</label>
<input id='user_id' type='text' name='user_id'>
<label for='user_pass'>张贴/删除密码:</label>
<input id='user_pass' type='password' name='user_pass'><br/>
<input type='submit' value='张贴'>
<input type='reset' value='清除重填'>
</form>
</div>
{% endblock %}
1
2
3
4
5
6
7
8
9
10
11
12
13
from django import forms
from . import models
class PostForm(forms.ModelForm):
class Meta:
model = models.Post //告诉model 与那个模型耦合
fields = ['mood','nickname','message','del_pass'] //需要显示的data

def __init__(self,*args,**kwargs):
super().__init__(self,*args,**kwargs)
self.fields['mood'].label = '现在的心情'
self.fields['nickname'].label = '您的昵称'
self.fields['message'].label = '心情留言'
self.fields['del_pass'].label = '设置密码'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-----------------------------------------------------------------------------------------<!--post2db.html-->
{% extends "base.html" %}
{% block title %}我有话要说{% endblock %}
{% block content %}
<div class='container'>
{% if message %}
<div class='alert alert-warning'>{{ message }}</div>
{% endif %}

<form name='my form' action='/' method='POST'>
{% csrf_token %}
<table>
{{ post_form.as_table}} //省去了前端对表格的代码
</table>
<input type="submit" value="张贴">
<input type="reset" value="重填">
</form>
</div>
{% endblock %}
△同时用ModelForm 的还有一好处为:并没有特别处理’‘现在的心情’'那部分,但ModelForm自动帮我们处理好了,外键的字段自动获得数据,并自动成为下拉式菜单

提交的数据接收:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
基本窗体:

<form method="GET">
# 所以获取数据为: user_id = request.GET['user_id']

<form method="POST">
# user_id = request.POST['user_id']

自定义窗体:(Form类)

<form method= 'POST'>
# form(实例).cleaned_data['user_id']

ModelForm :

post_form.save()

数据的保存:

基本窗体:

1
2
3
mood = models.Mood.objects.get(status=user_mood)
post = models.Post.objects.create(mood=mood, nickname=user_id, message=user_post, del_pass=user_pass)
post.save()

ModelForm:

1
post_form.save()

验证码功能(Django-simple-captcha):

  1. 安装Django-simple-captcha

  2. INSTALL_APPS中添加

  3. python manage.py migrate

  4. url(r'^captcha/',include('captcha.urls')),

  5. 安装Pillow

  6. 1
    2
    3
    4
    class PostForm(forms.ModelForm):
    captcha = CaptchaField()
    def __init__(self,*args,**kwargs):
    self.fields['captcha'].label = '验证码'

1
2
3
4
5
6
> COLORS = [
> ['黄','黄'],
> ['白','白'],
> ['红','红'], //前面的是值,后面的是显示的选项
> ]
>

1
2
3
4
*render 与 render_to_response的区别*
return render(request, 'blog_add.html', {'blog': blog, 'form': form, 'id': id, 'tag': tag})
-----------------------------------------------------------------------------------------
return render_to_response('blog_add.html', {'blog': blog, 'form': form, 'id': id, 'tag': tag})

render比render_to_response少填一个request参数


1
2
3
4
5
request.session['username'] = user.name			//设置session
if 'username' in request.session:
username = request.session['username'] //取出session

del request.session['username'] //删除session
1
2
3
4
5
6
7
8
if username: response.set_cookie('username',username)	//设置Cookie
//django1.11需要加encoding('utf-8'),2.0不需要
if 'username' in request.COOKIES and 'usercolor' in request.COOKIES:
username = request.COOKIES['username'] //取出COOKIE

def logout(request):
response = HttpResponseRedirect('/')
response.delete_cookie('username') //删除cookie

Django的信息显示框架:messages framework
1
2
3
from django.contrib import messages
主要提供两个函数: messages.add_message(request,messages.SUCCESS,'成功登陆了!')
messages.get_messages(request) ▲注意message后面有没有s

add_message()信息的内容类型默认分成以下几个等级:

  • DEBUG 调试信息字符串
  • INFO 信息字符串
  • SUCCESS 成功信息字符串
  • WARNING 警告信息字符串
  • ERROR 错误信息字符串

Django auth用户验证

from django.contrib.auth.models import User

主要提供三个函数:

  • authenticate(yz = input ,[]) //验证

  • login(request,user) //将数据存入Session,user为authenticate的返回值

  • logout(request)

    if user.is_active //检查账号是否有效,也没有括号

1
2
3
4
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib import auth //为了避免和自定义的 login.logout重名
from django.contrib.auth.decorators import login_required

验证session是否存在:

1
2
if request.user.is_authenticated:			
#▲1.11不加(),2.0可加可不加

需要登录才能浏览

1
@login_required(login_url='/login/')

增加auth的User字段

1
2
3
4
5
6
7
8
9
10
11
12
models.py中
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
height = models.PositiveIntegerField(default=60)
male = models.BooleanField(default=False)
website = models.URLField(null=True)

admin.py中
admin.site.register(models.Profile)

terminal: python mange.py migrate\makemigrations

显示增加的User字段

1
2
3
4
5
6
7
8
9
10
11
12
@login_required(login_url='/login/')
def userinfo(request):
if request.user.is_authenticated:
username = request.user.username
try:
user = User.objects.get(username = username)
userinfo = models.Profile.objects.get(user = user)
except:
pass
template = get_template('userinfo.html')
html = template.render(locals())
return HttpResponse(html)

点击的方式输入日期:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class DateInput(forms.DateInput):			//不是forms.DateField
input_type = 'date'

class DiaryForm(forms.ModelForm):
class Meta:
model = models.Diary
fields = ['budget','weight','note','ddate'] #没有指出user字段...通过ORM取出
widgets = {
'ddate':DateInput(),
}

def __init__(self,*args,**kwargs):
super(DiaryForm,self).__init__(*args,**kwargs)
self.fields['budget'].label = '今日话费(元)'
self.fields['weight'].label = '今日体重(KG)'
self.fields['note'].label = '心情留言'
self.fields['ddate'].label = '日期'

1
2
3
4
5
6
7
8
9
class Diary(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
budget = models.FloatField(default=0)
weight = models.FloatField(default=0)
note = models.TextField()
ddate = models.DateField()

def __str__(self):
return '{}{}'.format(self.ddate,self.user)

1
2
3
user = User.objects.get(username = username)	//DiaryFrom中没有user,通过Django的ORM取出
diary= models.Diary(user=user)
post_form = forms.DiaryForm(request.POST,instance=diary) //把所有信息合并

建立django-registration所需的模板:

模板或文件名 用途说明
registration_form.html 显示注册窗体的页面,默认使用form变量作为窗体各字段的内容
registration_complete.html 填写完注册窗体,单击’提交’按钮后显示的信息页面
activation_complete.html 当账号顺利完成启用时会显示的页面
activate.html 当账号顺利启用失败时会显示的页面
activation_email.txt 在发送启用邮件时使用的邮件内容
activation_email_subject.txt 在发送启用邮件时使用的邮件主题

Markdown

使用命令 pip install markdown 安装

将 Markdown 格式的文本渲染成 HTML 文本:

1
2
3
4
5
6
7
8
9
10
11
12
13
blog/views.py
import markdown
from django.shortcuts import render, get_object_or_404
from .models import Post
def detail(request, pk):
post = get_object_or_404(Post, pk=pk) # 记得在顶部引入 markdown 模块
post.body = markdown.markdown(post.body,
extensions=[
'markdown.extensions.extra',
'markdown.extensions.codehilite',#语法高亮拓展
'markdown.extensions.toc', #自动生成目录
])
return render(request, 'blog/detail.html', context={'post': post})

​ Django 出于安全方面的考虑,任何的 HTML 代码在 Django 的模板中都会被转义(即显示原始的 HTML 代码,而不是经浏览器渲染后的格式)。为了解除转义,只需在模板标签使用 safe 过滤器即可,告诉 Django,这段文本是安全的,你什么也不用做。

代码高亮

pip install Pygments 安装

Pygments 的工作原理是把代码切分成一个个单词,然后为这些单词添加 css 样式,不同的词应用不同的样式,这样就实现了代码颜色的区分,即高亮了语法。

Author: Mrli

Link: https://nymrli.top/2018/10/24/Python Web——Django笔记(二)/

Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

< PreviousPost
Python Web——Django笔记(一)
NextPost >
网络宽带和网络延迟
CATALOG
  1. 1. Method= POST的操作
  2. 2. 窗体Form与ModelForm区别
    1. 2.0.1. △同时用ModelForm 的还有一好处为:并没有特别处理’‘现在的心情’'那部分,但ModelForm自动帮我们处理好了,外键的字段自动获得数据,并自动成为下拉式菜单
  • 3. 提交的数据接收:
  • 4. 数据的保存:
  • 5. 验证码功能(Django-simple-captcha):
    1. 5.1. Django的信息显示框架:messages framework
    2. 5.2. Django auth用户验证
  • Markdown
    1. 0.1. 代码高亮